package com.byit.jwt.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.byit.jwt.domain.JwtSession;
import com.byit.utils.SpringUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * JWT实现工具类
 *
 * @author marker
 **/
public class JWTUtil {


    /**
     * Session 手机号
     */
    private static final String MOBILE = "mb";

    /**
     * Session 会员Id
     */
    private static final String MEMBER_ID = "mid";
    private static final String COMPANY_ID = "cid";


    /**
     * 校验token是否正确
     *
     * @param token  密钥
     * @param secret 用户的密码
     * @return 是否正确
     */
    public static boolean verify(String token, String secret, JwtSession session) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim(MOBILE, session.mobile())
                    .withClaim(MEMBER_ID, session.userId())
                    .build();
            verifier.verify(token);

            return true;
        } catch (Exception exception) {
            return false;
        }
    }


    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的手机号
     */
    public static String getMobile() {
        Subject subject = SecurityUtils.getSubject();
        String token = subject.getPrincipal().toString();
        return getMobile(token);
    }


    public static String getMobile(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(MOBILE).asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }


    /**
     * 获取会话的MemberId
     *
     * @return
     */
    public static Long getMemberId() {
        Subject subject = SecurityUtils.getSubject();
        String token = subject.getPrincipal().toString();
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(MEMBER_ID).asLong();
        } catch (JWTDecodeException e) {
            return null;
        }
    }


    public static Integer getCompanyId() {
        Subject subject = SecurityUtils.getSubject();
        String token = subject.getPrincipal().toString();
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(COMPANY_ID).asInt();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成签名,5min后过期
     *
     * @param secret 用户的密码
     * @return 加密的token
     */
    public static String sign(String secret, JwtSession session) {
        try {
            Date date = new Date(System.currentTimeMillis() + 5);
            Algorithm algorithm = Algorithm.HMAC256(secret);
            // 附带username信息
            return JWT.create()
                    .withClaim(MOBILE, session.mobile())
                    .withClaim(MEMBER_ID, session.userId())
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }


    /**
     * 获取Session
     *
     * @return
     */
    public static JwtSession getSession(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);

            return JwtSession.builder()
                    .userId(jwt.getClaim(MEMBER_ID).asLong())
                    .mobile(jwt.getClaim(MOBILE).asString());
        } catch (JWTDecodeException e) {
            return null;
        }
    }


}
